package com.sxkiler.demo.maintest.management;

import java.lang.management.*;
import java.lang.management.ManagementFactory;
import java.util.HashMap;
import java.util.Map;

public class CPUMonitorCalc {


    public CPUMonitorCalc() {   }
    private int sampleTime = 300;
    private ThreadMXBean threadMxBean = java.lang.management.ManagementFactory.getThreadMXBean();
    private RuntimeMXBean runtimeMxBean = java.lang.management.ManagementFactory.getRuntimeMXBean();
    private OperatingSystemMXBean osMxBean = ManagementFactory.getOperatingSystemMXBean();
    private Map<Long, Long> threadInitialCPU = new HashMap<Long, Long>();
    private Map<Long, Float> threadCPUUsage = new HashMap<Long, Float>();
    com.sun.management.OperatingSystemMXBean osBean = ManagementFactory
            .getPlatformMXBean(com.sun.management.OperatingSystemMXBean.class);

    public void getCpuRate(){
        long initialUptime = runtimeMxBean.getUptime();
        //计算初始信息
        long initialCpuTime = osBean.getProcessCpuTime();
        ThreadInfo[] threadInfos = threadMxBean.dumpAllThreads(false, false);
        for (ThreadInfo info : threadInfos) {
            threadInitialCPU.put(info.getThreadId(), threadMxBean.getThreadCpuTime(info.getThreadId()));
        }
        //sleep一段时间
        try {Thread.sleep(sampleTime);} catch (InterruptedException e) {}
        //计算线程cpu
        long upTime = runtimeMxBean.getUptime();
        Map<Long, Long> threadCurrentCPU = new HashMap<Long, Long>();
        for (ThreadInfo info : threadInfos) {
            threadCurrentCPU.put(info.getThreadId(), threadMxBean.getThreadCpuTime(info.getThreadId()));
        }
        //CPU over all processes
//        int nrCPUs = 1;
        int nrCPUs = osMxBean.getAvailableProcessors();
        //total CPU: CPU % can be more than 100% (devided over multiple cpus)

        //elapsedTime is in ms.
        long elapsedTime = (upTime - initialUptime);
        for (ThreadInfo info : threadInfos) {
            //elapsedCpu is in ns
            Long initialCPU = threadInitialCPU.get(info.getThreadId());
            if (initialCPU!= null) {
                long elapsedCpu = threadCurrentCPU.get(info.getThreadId()) - initialCPU;
                float cpuUsage = elapsedCpu/(elapsedTime * 1000000F * nrCPUs) * 100;
                threadCPUUsage.put(info.getThreadId(), cpuUsage);
            }
        }
        long elapsedCpuime = osBean.getProcessCpuTime() - initialCpuTime;
        float cpuUsage = elapsedCpuime/(elapsedTime * 1000000F * nrCPUs) * 100;
        System.out.println("systemCpuRate="+cpuUsage);
        System.out.println(osBean.getProcessCpuLoad());
        System.out.println(osBean.getSystemCpuLoad());
        //threadCPUUsage contains cpu % per thread
        System.out.println(threadCPUUsage);
    }
//You can use osMxBean.getThreadInfo(theadId) to get information on every thread reported in threadCPUUsage and analyze the most CPU intentive threads


}